import os
import requests
import shutil
try:
    from .cvio import cvio
    from .testService import encodeImg
    from .running_faster import Runner
except:
    from cvio import cvio
    from testService import encodeImg
    from running_faster import Runner

def detect_img_qua_ass(img, url, i, n, dst, sizeDegree=1, blurDegree=1, 
    yawDegree=1, brightnessDegree=1, recaptureDegree=1, nondisplayDegree=1):
    imgId = os.path.basename(img)
    print('[%d/%d]' % (i, n), url, imgId)
    base64Data = str(encodeImg(img), encoding='utf-8')
    data = {'base64Data': base64Data, 'imageId': imgId}
    res = requests.post(url=url, json=data).json()
    if not res['status']:
        print('Detect failed,', imgId)
        return False
    
    flag = True
    if sizeDegree not in (None, '', -1):
        flag = flag and (sizeDegree ==  int(res['data']['result']['sizeDegree']))
    if blurDegree not in (None, '', -1):
        flag = flag and (blurDegree ==  int(res['data']['result']['blurDegree']))
    if yawDegree not in (None, '', -1):
        flag = flag and (yawDegree ==  int(res['data']['result']['yawDegree']))
    if brightnessDegree not in (None, '', -1):
        flag = flag and (brightnessDegree ==  int(res['data']['result']['brightnessDegree']))
    if recaptureDegree not in (None, '', -1):
        flag = flag and (recaptureDegree ==  int(res['data']['result']['recaptureDegree']))
    if nondisplayDegree not in (None, '', -1):
        flag = flag and (nondisplayDegree ==  int(res['data']['result']['nondisplayDegree']))

    if flag:
        shutil.copy(img, os.path.join(dst, imgId))

def detect_imgs_qua_ass(url, src, dst, worker='process', num_workers=8, sizeDegree=1, blurDegree=1, 
    yawDegree=1, brightnessDegree=1, recaptureDegree=1, nondisplayDegree=1):
    imgs = cvio.load_image_list(src)
    n = len(imgs)
    if n < 1:
        return

    if not os.path.exists(dst):
        os.makedirs(dst)

    runner = Runner()
    for i, img in enumerate(imgs, 1):
        runner.append(detect_img_qua_ass, (img, url, i, n, dst, sizeDegree, blurDegree, 
    yawDegree, brightnessDegree, recaptureDegree, nondisplayDegree))

    runner.run(mode=worker, num_workers=num_workers)

if __name__ == '__main__':
    img = r'G:\data\datasets\drink\daiding_101\train\mask\yy_20210601_11809.jpg'
    url = 'http://172.16.73.202:9999/imgQuaAss'
    detect_img_qua_ass(img, url)